package com.leenmvc.core.init;

import com.leenmvc.core.annotation.ApiDescription;
import com.leenmvc.core.base.BaseEntity;
import com.leenmvc.core.cache.CacheFactory;
import com.leenmvc.core.dao.mysql.MysqlBaseDaoImpl;
import com.leenmvc.core.dao.mysql.wrapper.QueryWrapper;
import com.leenmvc.core.enums.CacheType;
import com.leenmvc.core.security.entity.core.SysLanguage;
import com.leenmvc.core.security.entity.core.SysMenu;
import com.leenmvc.core.security.entity.core.SysTip;
import com.leenmvc.core.utils.dictionary.Dict;
import com.leenmvc.core.utils.http.entity.UrlData;
import com.leenmvc.core.utils.spring.SpringContextUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

/**
 * 初始化包括表、项目中的值到内存中
 */
public class InitValue {

    private static MysqlBaseDaoImpl baseDao = MysqlBaseDaoImpl.getInstance();

    /**
     * 初始化数据数据到内存中
     */
    public static void initDbValue() {
        // 初始化字典表到内存中
        String[] types = new String[]{"SYSTEM","service_config", "rtmp"};
        for(String type: types) {
            Map<String, Object> dictType = Dict.getMapByType(type);
            CacheFactory.put(CacheType.GLOBAL_VARIABLE, type, dictType);
            for(String key: dictType.keySet()) {
                if("true".equals(dictType.get(key)) || "false".equals(dictType.get(key))) {
                    CacheFactory.putStatus(key, Boolean.parseBoolean(dictType.get(key).toString()));
                }
            }
        }

        // 初始化国际化提示语
        Class<?>[] tables = new Class<?>[]{SysTip.class, SysMenu.class};
        Map<String, Map<String, Map<String, Object>>> tips = new HashMap<>();
        for(Class table: tables) {
            String tableName = BaseEntity.getTableName(table);
            List<SysLanguage> languages = baseDao.getList(SysLanguage.class, "tableName", tableName);
            Set<Long> tableids = new HashSet<>();
            Map<String, Map<String, Object>> tip = new HashMap<>();
            for (SysLanguage language : languages) {
                if (tableids.contains(language.getId())) continue;
                String fieldValue = null;
                if(SysTip.class.equals(table)) {
                    QueryWrapper queryW = BaseEntity.getDialect(SysTip.class).getWrapperFactory().getQueryWrapper(table);
                    queryW.eq("id", language.getTableId());
                    queryW.incField(language.getFieldName());
                    fieldValue = baseDao.getOneField(queryW);
                } else {
                    fieldValue = language.getTableId().toString();
                }
                List<SysLanguage> languageL = baseDao.getList(SysLanguage.class, "tableId", language.getTableId());
                Map<String, Object> temp = new HashMap<>();
                for (SysLanguage l : languageL) {
                    temp.put(l.getLanguage(), l.getFieldValue());
                    tableids.add(l.getId());
                }
                tip.put(fieldValue, temp);
            }
            tips.put(tableName, tip);
        }
        CacheFactory.put(CacheType.GLOBAL_VARIABLE, "tips", tips);
    }

    /**
     * 初始化
     */
    public static void initUrl() {
        RequestMappingHandlerMapping mapping = SpringContextUtils.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) { // 非公共控制器的URL
            UrlData urlData = new UrlData();
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                urlData.setUrl(url);
            }
            Class<?> cls = method.getMethod().getDeclaringClass();
            urlData.setCls(cls); // 类名
            urlData.setMethod(method.getMethod()); // 方法名
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                urlData.setRequestMethod(requestMethod.toString());
            }
            ApiDescription annotation = cls.getAnnotation(ApiDescription.class);
            if(annotation != null) {
                urlData.setModule(annotation.value());
            } else {
                urlData.setModule("未指定模块");
            }
            CacheFactory.put(CacheType.URL_INFO, urlData.getUrl(), urlData);
            CacheFactory.put(CacheType.URL_INFO, urlData.getCls().getSimpleName(), urlData);
        }

    }

}
